package cn.iocoder.yudao.module.book.controller.admin.images;
import cn.iocoder.yudao.module.book.util.MinioUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

// removed unused javax.validation.constraints import
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.book.controller.admin.images.vo.*;
import cn.iocoder.yudao.module.book.dal.dataobject.images.bookImagesDO;
import cn.iocoder.yudao.module.book.service.images.bookImagesService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 绘本页")
@RestController
@RequestMapping("/book/book-images")
@Validated
public class bookImagesController {

    @Resource
    private bookImagesService bookImagesService;

    @Resource
    private MinioUtils minioUtils;

    @PostMapping("/create")
    @Operation(summary = "创建绘本页")
    @PreAuthorize("@ss.hasPermission('book:book-images:create')")
    public CommonResult<Integer> createbookImages(@Valid @RequestBody bookImagesSaveReqVO createReqVO) {
        return success(bookImagesService.createbookImages(createReqVO));
    }

    @PostMapping("/create-with-image")
    @Operation(summary = "创建中英文绘本（带图片）")
    @PreAuthorize("@ss.hasPermission('book:s:create')")
    public CommonResult<Integer> createImage(
            @Valid bookImagesSaveReqVO saveReqVO,
            @Parameter(description = "绘本图片", required = true)
            @RequestParam("imageFile") MultipartFile imageFile) {
        try {
            // 上传图片到MinIO
            List<String> fileNames = minioUtils.upload(new MultipartFile[]{imageFile});
            if (fileNames.isEmpty()) {
                return CommonResult.error(500,"图片上传失败");
            }

            // 构建BooksDO对象
            bookImagesDO image = new bookImagesDO();
            // 设置书籍基本信息
            image.setImageOrder(saveReqVO.getImageOrder());

            // 设置图片URL（需要根据MinIO访问策略构建完整URL）
            String imageUrl = buildImageUrl(fileNames.get(0));
            image.setImageUrl(imageUrl);

            // 调用原有的创建方法
            return CommonResult.success(bookImagesService.createbookImages(saveReqVO));
        } catch (Exception e) {
            return CommonResult.error(500,"图片上传失败");
        }
    }

    private String buildImageUrl(String fileName) {
        // 根据MinIO配置构建完整的图片访问URL
        // 示例: http://minio-endpoint/bucket-name/filename
        return "http://192.168.110.128:9000/abc/" + fileName;
    }

    @PutMapping("/update")
    @Operation(summary = "更新绘本页")
    @PreAuthorize("@ss.hasPermission('book:book-images:update')")
    public CommonResult<Boolean> updatebookImages(@Valid @RequestBody bookImagesSaveReqVO updateReqVO) {
        bookImagesService.updatebookImages(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除绘本页")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('book:book-images:delete')")
    public CommonResult<Boolean> deletebookImages(@RequestParam("id") Integer id) {
        bookImagesService.deletebookImages(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得绘本页")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('book:book-images:query')")
    public CommonResult<bookImagesRespVO> getbookImages(@RequestParam("id") Integer id) {
        bookImagesDO bookImages = bookImagesService.getbookImages(id);
        return success(BeanUtils.toBean(bookImages, bookImagesRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得绘本页分页")
    @PreAuthorize("@ss.hasPermission('book:book-images:query')")
    public CommonResult<PageResult<bookImagesRespVO>> getbookImagesPage(@Valid bookImagesPageReqVO pageReqVO) {
        PageResult<bookImagesDO> pageResult = bookImagesService.getbookImagesPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, bookImagesRespVO.class));
    }

    @GetMapping("/orders")
    @Operation(summary = "根据书ID获取绘本页（按顺序返回）")
    @PreAuthorize("@ss.hasPermission('book:book-images:query')")
    public CommonResult<List<bookImagesRespVO>> listOrderedByBook(@RequestParam("bookId") Integer bookId) {
        bookImagesPageReqVO reqVO = new bookImagesPageReqVO();
        reqVO.setBookId(bookId);
        reqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<bookImagesDO> pageResult = bookImagesService.getbookImagesPage(reqVO);
        List<bookImagesRespVO> list = BeanUtils.toBean(pageResult.getList(), bookImagesRespVO.class);
        // 以 imageOrder 升序返回，空值在最后
        list.sort(Comparator.comparing(bookImagesRespVO::getImageOrder, Comparator.nullsLast(Integer::compareTo)));
        return success(list);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出绘本页 Excel")
    @PreAuthorize("@ss.hasPermission('book:book-images:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportbookImagesExcel(@Valid bookImagesPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<bookImagesDO> list = bookImagesService.getbookImagesPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "绘本页.xls", "数据", bookImagesRespVO.class,
                        BeanUtils.toBean(list, bookImagesRespVO.class));
    }

}